#pragma once

#include <string>
#include <functional>

#include "Reactor.hpp"

class connection;
using func_t = std::function<void(connection *)>;

// 描述连接的类
class connection
{
public:
    connection(int fd)
    : _fd(fd)
    {
    }

    void Register(func_t recever, func_t sender, func_t excepter)
    {
        _recever = recever;
        _sender = sender;
        _excepter = excepter;
    }

    void setReactor(reactor* r)
    {
        _r = r;
    }

    void setEvent(uint32_t event)
    {
        _event = event;
    }

    int getFd()
    {
        return _fd;
    }

    uint32_t getEvent()
    {
        return _event;
    }

    void appendInbuffer(const std::string& buffer)
    {
        _inbuffer += buffer;
    }

    void appendOutbuffer(const std::string& buffer)
    {
        _outbuffer += buffer;
    }
    
    std::string& getInbuffer()
    {
        return _inbuffer;
    }

    std::string& getOutbuffer()
    {
        return _outbuffer;
    }

    bool outbufferEmpty()
    {
        return _outbuffer.size() == 0;
    }

    void removeOutbuffer(int n)
    {
        _outbuffer.erase(0, n);
    }

    void closeFd()
    {
        if (_fd >= 0)
            ::close(_fd);
    }

    ~connection()
    {
    }

private:
    int _fd;                // 连接的文件描述符fd
    std::string _inbuffer;  // 输入缓冲区
    std::string _outbuffer; // 输出缓冲区
    uint32_t _event;         //该文件描述符关心的事件
public:
    func_t _recever;  // 读方法
    func_t _sender;   // 写方法
    func_t _excepter; // 错误处理

    reactor *_r;
};